package com.tanhua.dubbo.api;

import com.tanhua.dubbo.utils.IdWorker;
import com.tanhua.mongo.Video;
import com.tanhua.vo.PageResult;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

import java.util.List;

@DubboService
public class VideoApiImpl implements VideoApi {
    @Autowired
    private MongoTemplate mongoTemplate;

    @Autowired
    private IdWorker idWorker;

    /**
     * 保存小视频，返回对应视频id
     *
     * @param video
     * @return
     */
    @Override
    public String save(Video video) {
        video.setVid(idWorker.getNextId("video"));
        video.setCreated(System.currentTimeMillis());
        mongoTemplate.save(video);
        return video.getId().toHexString();
    }

    /**
     * 通过id查询小视频
     * @param ids
     * @return
     */
    @Override
    public List<Video> findByIds(List<Long> ids) {
        Query query = Query.query(Criteria.where("vid").in(ids));
        return mongoTemplate.find(query,Video.class);
    }

    /**
     * 分页查询小视频
     * @param page
     * @param pagesize
     * @return
     */
    @Override
    public List<Video> queryVideoList(int page, Integer pagesize) {
        Query query = new Query().skip((page - 1) * pagesize).limit(pagesize)
                .with(Sort.by(Sort.Order.desc("created")));
        return mongoTemplate.find(query,Video.class);
    }

    /**
     * 查询用户视频
     * @param uid
     * @param page
     * @param pagesize
     * @return
     */
    @Override
    public PageResult findAllVideos(Long uid, Integer page, Integer pagesize) {
        Query query = Query.query(Criteria.where("userId").is(uid));
        long count = mongoTemplate.count(query, Video.class);
        query.skip((page - 1) * pagesize).limit(pagesize)
                    .with(Sort.by(Sort.Order.desc("created")));
        List<Video> list = mongoTemplate.find(query, Video.class);
        return new PageResult(page,pagesize,count,list);
    }
}
